//! gRPC客户端使用示例
//! 
//! 展示如何使用gRPC客户端调用沙箱管理服务

use anyhow::Result;
use koda_sandbox_manager::grpc::{SandboxManagerClientBuilder, Language, Priority, ResourceRequirements};

#[tokio::main]
async fn main() -> Result<()> {
    println!("🔗 连接到gRPC沙箱管理服务器...");
    
    // 创建客户端
    let mut client = SandboxManagerClientBuilder::new("http://127.0.0.1:50051")
        .build()
        .await?;
    
    println!("✅ 成功连接到服务器");
    
    // 1. 健康检查
    println!("\n🏥 执行健康检查...");
    let health = client.health_check().await?;
    println!("健康状态: {:?}", health.status);
    println!("服务版本: {}", health.version);
    
    // 2. 分配沙箱
    println!("\n📦 分配Python沙箱...");
    let sandbox = client.allocate_sandbox(
        Language::Python,
        "3.9".to_string(),
        Some(ResourceRequirements {
            memory_mb: 512,
            cpu_cores: 1,
            disk_mb: 1024,
            network_enabled: true,
        }),
        300, // 5分钟超时
        Priority::Normal,
    ).await?;
    
    println!("✅ 成功分配沙箱: {}", sandbox.sandbox_id);
    println!("沙箱状态: {:?}", sandbox.state);
    
    // 3. 执行代码
    println!("\n💻 执行Python代码...");
    let result = client.execute_code(
        sandbox.sandbox_id.clone(),
        "print('Hello from Koda Sandbox!')".to_string(),
        Language::Python,
        "main".to_string(),
        std::collections::HashMap::new(),
        "".to_string(),
        5000, // 5秒超时
    ).await?;
    
    println!("执行结果:");
    println!("  成功: {}", result.success);
    println!("  输出: {}", result.stdout);
    if !result.stderr.is_empty() {
        println!("  错误: {}", result.stderr);
    }
    println!("  执行时间: {}ms", result.execution_time_ms);
    
    // 4. 获取沙箱状态
    println!("\n📊 获取沙箱状态...");
    let status = client.get_sandbox_status(sandbox.sandbox_id.clone()).await?;
    println!("沙箱ID: {}", status.sandbox_id);
    println!("当前状态: {:?}", status.state);
    println!("使用次数: {}", status.usage_count);
    
    // 5. 获取系统统计
    println!("\n📈 获取系统统计信息...");
    let stats = client.get_system_stats().await?;
    println!("总沙箱数: {}", stats.total_sandboxes);
    println!("活跃沙箱数: {}", stats.active_sandboxes);
    
    // 6. 释放沙箱
    println!("\n🗑️ 释放沙箱...");
    let release_result = client.release_sandbox(sandbox.sandbox_id).await?;
    println!("释放结果: {}", release_result.success);
    println!("释放消息: {}", release_result.message);
    
    println!("\n✅ gRPC客户端示例完成！");
    
    Ok(())
}